package net.app.zoneland.file.controller;

import io.minio.PutObjectOptions;
import io.minio.errors.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import net.app.zoneland.common.core.vo.Result;
import net.app.zoneland.file.utils.MinIoUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author LENOVO
 * @CreateTime 2021/1/1 16:32
 * @Version: 1.0
 */
@Api(tags = "文件上传接口")
@RestController
@AllArgsConstructor
@RequestMapping("/file")
public class FileController {

    private final MinIoUtils minIoUtils;

    /**
     * 文件批量上传
     * @return
     */
    @ApiOperation(value = "使用minio文件上传(支持多个文件和单个文件的上传)")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "MultipartFile", name = "files", value = "上传的图片", required = true),
            @ApiImplicitParam(dataType = "String", name = "bucketName", value = "对象存储桶名称", required = true)
    })
    @PostMapping("/upload")
    public Result uploadFiles(MultipartFile[] files, String bucketName){
        Map<String,String> params=new HashMap<String,String>();
        if(bucketName!=null){
            for (MultipartFile file : files) {
                System.out.println("上传文件名:"+file);

                InputStream is = null;
                try {
                     is = file.getInputStream(); //得到文件流
                String fileName = file.getOriginalFilename();
                String contentType = file.getContentType();  //类型
                PutObjectOptions options = new PutObjectOptions(file.getSize(), PutObjectOptions.MIN_MULTIPART_SIZE);
                                 options.setContentType(contentType);
                    String url = minIoUtils.putObject(bucketName, fileName, is, options);
                    System.out.println("上传文件名:"+fileName);
                    System.out.println("服务器路径:"+url);
                    params.put(fileName,url);
                }catch(IOException e){
                    e.printStackTrace();
                }finally {
                    try {
                        if (is != null) {
                            is.close();
                        }
                    }catch (IOException ex){
                        ex.printStackTrace();
                    }
                }
            }
        }
        return Result.success(params);
    }

    /**
     * 单文件上传
     * @return
     */
    @ApiOperation(value = "使用minio单文件上传")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "MultipartFile", name = "file", value = "上传的图片", required = true),
            @ApiImplicitParam(dataType = "String", name = "bucketName", value = "对象存储桶名称", required = true)
    })
    @PostMapping("/uploadFile")
    public Result uploadFile(@RequestParam("file") MultipartFile file){
        String bucketName="test";
        if(bucketName!=null){
            InputStream input=null;
            try {
                input = file.getInputStream();//得到文件流
                String fileName = file.getOriginalFilename();
                String contentType = file.getContentType();  //类型
                PutObjectOptions options = new PutObjectOptions(file.getSize(), PutObjectOptions.MIN_MULTIPART_SIZE);
                options.setContentType(contentType);
                String url = minIoUtils.putObject(bucketName, fileName, input, options);
                return Result.success(url);
            }catch (IOException e){
                e.printStackTrace();
            }finally {
                try{
                    if(input!=null){
                        input.close();
                    }
                }catch (IOException ex){
                    ex.printStackTrace();
                }
            }
        }
        return Result.error("文件上传出错啦!");
    }

    @ApiOperation(value = "使用minio删除附件")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "bucketName", value = "对象存储桶名称", required = true),
            @ApiImplicitParam(dataType = "String", name = "fileName", value = "文件名", required = true)
    })
    @DeleteMapping("/delFile/{bucketName}/{fileName}")
    public Result delFile(@PathVariable String bucketName,@PathVariable String fileName){
        if(bucketName!=null && fileName!=null){
            try {
                minIoUtils.removeObject(bucketName, fileName);
                return Result.success();
            }catch (IOException | InvalidResponseException | InvalidKeyException | NoSuchAlgorithmException | ErrorResponseException | XmlParserException | InvalidBucketNameException | InsufficientDataException | InternalException e){
                e.printStackTrace();
            }
            return Result.error("删除失败");
        }
        return Result.error("参数不可为空");
    }
}
